package com.h2cloud.threadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Package: com.h2cloud.threadPool
 * @ClassName: myTreadPoolExecutor
 * @Author: h2cloud
 * @CreateTime: 2022/9/28 11:36 下午
 * @Description:
 */
class myTreadPoolExecutor extends ThreadPoolExecutor {

	public myTreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
	}

	@Override
	protected void afterExecute(Runnable r, Throwable t) {
		super.afterExecute(r, t);
		if (t == null && r instanceof Future) {
			try {
				Object result = ((Future) r).get();
			} catch (CancellationException ce) {
				t = ce;
			} catch (ExecutionException ee) {
				t = ee.getCause();
			} catch (InterruptedException ie) {
				Thread.currentThread().interrupt(); // ignore/reset
			}
		}
		if (t != null) {
			System.out.println(t);
		}
	}

	public static void main(String[] args) {
		// test();
		System.out.println("main");
	}

	public static void test() {
		ExecutorService executorService = new myTreadPoolExecutor(15, 30, 60L,
				TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), r -> new Thread(r, "my asyn task"));

		List<Future<?>> futureList = new ArrayList();
		// The number of tasks will not exceed 1024
		for (int i = 0; i < 10; i++) {
			Future<?> future = executorService.submit(() -> {
				// Execute my business logic
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("this task is end");
			});
			futureList.add(future);
		}

		//子线程不停gc，模拟偶发的gc
		new Thread(() -> {
			while (true) {
				System.gc();
			}
		}).start();

		futureList.forEach(f -> {
			try {
				System.out.println("f.get()");
				f.get(); // Occasionally, it keeps blocking here, and the main thread cannot continue to execute
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		});
		System.out.println("test wait end");
	}

}
